﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Text;

namespace JugglingMvc.Models
{
    public class JugglersRepository
    {
        private JugglersDataContext dataContext = new JugglersDataContext();

        public Juggler GetJuggler(int id)
        {
            return dataContext.Jugglers.SingleOrDefault(d => d.Id == id);
        }
        // Query Methods
        public IQueryable<Juggler> FindAllJugglers()
        {
            return dataContext.Jugglers;
        }

        public IQueryable<Specialty> GetSpecialities()
        {
            return dataContext.Specialties;
                  
        }




        public IQueryable<Team> GetTeams()
        {
            return  dataContext.Teams;

        }
        public String GetTeamNameById(int teamId)
        {
            var res = dataContext.Teams.SingleOrDefault(d => d.Id == teamId);
            var res2 = res ?? new Team { Id = -1, Name = "Ninguno" };
            return res2.Name;

        }

        public String GetSpecialityNameById(int specialityId)
        {
            var res = dataContext.Specialties.SingleOrDefault(d => d.Id == specialityId);
            var res2 = res ?? new Specialty { Name = "", Id = -1};
            return res2.Name;
        }

        public IQueryable<Juggler> FindExpertsIn(int specialityId)
        {
            return from juggler in dataContext.Jugglers
                   where juggler.SpecialtyId == dataContext.Specialties.SingleOrDefault(d => d.Id == specialityId).Id

                   select juggler;
        }
        //
        // Insert/Delete Methods
        public void Add(Juggler juggler)
        {
            dataContext.Jugglers.InsertOnSubmit(juggler);
        }
        public void Delete(Juggler juggler)
        {

            dataContext.Jugglers.DeleteOnSubmit(juggler);
        }

        public void Delete(Specialty speciality)
        {
            dataContext.Jugglers.DeleteAllOnSubmit(speciality.Jugglers);
            dataContext.Teams.DeleteAllOnSubmit(speciality.Teams);
            dataContext.Specialties.DeleteOnSubmit(speciality);
            //al borrar una especialidad se borran los
            //malabaristas que tienen esa especialidad
            //y los equipos que la tienen
        }


        public void Delete(Team team)
        {
            dataContext.Teams.DeleteOnSubmit(team);

        }

        //
        // Persistence
        public void Save()
        {
            dataContext.SubmitChanges();
        }
    }
}






